﻿/* ==============================================================================
*
*   Copyright (c) 2010, Pierre Favier
*   All rights reserved.
*
*   NTasking is free software: you can redistribute it and/or modify it
*   under the terms of the GNU General Public License as published by the
*   Free Software Foundation.
*
*   Redistribution and use in source and binary forms, with or without
*   modification, are permitted provided that the following conditions
*   are met:
*
*   -   Redistributions of source code must retain the above copyright notice,
*       this list of conditions and the following disclaimer.
*
*   -   Redistributions in binary form must reproduce the above
*       copyright notice, this list of conditions and the following
*       disclaimer in the documentation and/or other materials
*       provided with the distribution.
*
*   THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
*   WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
*   OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
*   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
*   BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
*   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
*   TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
*   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
*   ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
*   TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
*   THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
*   SUCH DAMAGE.
*
* ============================================================================== */

using System;
using System.Threading;

namespace NTasking.Internals
{

    /// <summary>
    /// A class which adds some functionality to the standard <see
    /// cref="ReaderWriterLock">ReaderWriterLock</see> class: 
    /// <list type="bullet">
    /// <item>
    /// <description>tracing of waiting/locking/unlocking
    /// operations</description></item>
    /// <item>
    /// <description>simplification of the locking through two methodes EnterLock and
    /// ExitLock </description></item></list>
    /// </summary>
    internal class NamedReaderWriterLockSlim : ReaderWriterLockSlim
    {

        #region Properties

        /// <summary>
        /// Gets or sets the <see cref="Protected"/> object which created this instance.
        /// </summary>
        /// <value>The referrer.</value>
        private Protected Referrer { get; set; }


        /// <summary>
        /// Gets or sets the name of this instance.
        /// </summary>
        /// <value>The name of this instance.</value>
        private string Name { get; set; }

        #endregion


        /// <summary>
        /// Initializes a new instance of the <see cref="NamedReaderWriterLockSlim"/> class.
        /// </summary>
        /// <param name="name">The name of this instance.</param>
        /// <param name="referrer">The  <see cref="Protected"/> object which created this instance.</param>
        internal NamedReaderWriterLockSlim(string name, Protected referrer)
        {
            Name = name;
            Referrer = referrer;
        }


#pragma warning disable 1587
#if TASKING_DEBUG

        /// <summary>
        /// Enters the lock in read-only mode.
        /// </summary>
        private new void EnterWriteLock()
        {
            if (!TryEnterWriteLock(0))
            {
                Tracer.Trace("Blocked on acquisition of " + this + " lock");
                EnterWriteLock();
            }
        }
#endif


#if TASKING_DEBUG
        /// <summary>
        /// Enters the lock in read-write mode.
        /// </summary>
        private new void EnterReadLock()
        {
            if (!TryEnterReadLock(0))
            {
                Tracer.Trace("Blocked on acquisition of " + this + " lock");
                EnterReadLock();
            }
        }
#endif


        /// <summary>
        /// Enters the lock.
        /// </summary>
        /// <param name="readOnly">if set to <c>true</c> enter the lock in rea-onlyd mode,
        /// otherwise enter the lock in read-write mode.</param>
        /// <param name="tryOnly">if set to <c>true</c> only get the lock if it is available,
        /// otherwise wait for the lock if it is not available.</param>
        internal void EnterLock(bool readOnly, bool tryOnly)
        {
            try
            {
                if (readOnly && tryOnly)
                    TryEnterReadLock(0);
                else if (readOnly)
                    EnterReadLock();
                else if (tryOnly)
                    TryEnterWriteLock(0);
                else
                    EnterWriteLock();
            }
            catch (ObjectDisposedException)
            {
                Errors.ProtectedHasBeenDisposed(Referrer);
            }
        }


        /// <summary>
        /// Exits the lock.
        /// </summary>
        internal void ExitLock()
        {
            if (IsReadLockHeld)
            {
                ExitReadLock();
            }
            else if (IsWriteLockHeld)
            {
                ExitWriteLock();
            }
        }


        /// <summary>
        /// Returns a <see cref="System.String"/> that represents this instance.
        /// </summary>
        /// <returns>
        /// A <see cref="System.String"/> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            return Name + "::" + Referrer;
        }

    }

}
